﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Login.OSIRISService;

namespace Login.Controllers
{
    /// <summary>
    /// The HomeController serves pages that are used by students
    /// when they log in to the system for the first time. It checks
    /// permission for a final internship and provides them with
    /// the possibility to continue with registering when they have
    /// permission.
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// Called when the Index action is requested using GET.
        /// </summary>
        /// <returns>The view or a redirect</returns>
        [Authorize(Roles="Student")]
        public ActionResult Index()
        {
            /* fetch StudentDetails from session */
            StudentDetails studentDetails = Session["Details"] as StudentDetails;

            /* connect to local database */
            AfstudeerregistratieDataContext database = new AfstudeerregistratieDataContext();

            /* define query */
            IEnumerable<Student> studentQuery =
                from dbStudent in database.Students
                where dbStudent.Number == studentDetails.Number
                select dbStudent;

            /* get student from query */
            Student student = studentQuery.First();

            /* if the student doesn't have permission from OSIRIS */
            if (!student.HasPermissionOSIRIS)
            {
                /* connect to the OSIRIS service */
                OSIRISServiceClient osiris = new OSIRISServiceClient();

                /* ask for permission */
                student.HasPermissionOSIRIS = osiris.AskForPermission(student.Number);

                /* close connection with OSIRIS */
                osiris.Close();

                /* submit changes */
                database.SubmitChanges();
            }

            /* if the student doesn't have permission */
            if (!student.HasPermissionOSIRIS || !student.HasPermissionSLB)
            {
                /* redirect to error message */
                return RedirectToAction("Permission");
            }

            /* return the view */
            return View();
        }

        /// <summary>
        /// Called when the Permission action is requested using GET.
        /// </summary>
        /// <returns>The view or a redirect</returns>
        [Authorize(Roles="Student")]
        public ActionResult Permission()
        {
            /* return the view */
            return View();
        }
    }
}
